package com.ansion.commonchat

import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import com.ansion.baseui.base.TVPBaseActivity
import com.ansion.commonchat.contact.systemcontact.MyCustomContract
import com.ansion.commonchat.contact.ui.ContactsFragmentNew
import com.ansion.commonchat.contact.utils.SyncDataProgressManager
import com.ansion.commonchat.presenter.SecondPresenter
import com.ansion.commonchat.request.GreeterGrpc
import com.ansion.commonchat.request.GreeterOuterClass
import com.ansion.commonchat.request.GreeterOuterClass.HelloRequest
import com.ansion.constant.BConstant
import com.ansion.log.VLog
import com.ansion.utils.ResourceUtils
import com.ansion.utils.ThreadUtil
import com.ansion.utils.permission.RealRxPermission
import io.grpc.ManagedChannelBuilder
import io.grpc.stub.StreamObserver


class SecondActivity : TVPBaseActivity<SecondPresenter>() {
    private lateinit var myCustomLauncher: ActivityResultLauncher<Int>
    override fun initContentView(savedInstanceState: Bundle?): Int {
        enableEdgeToEdge()
        return R.layout.activity_second
    }

    override fun createPresenter(): SecondPresenter {
        return SecondPresenter()
    }

    override fun initView(savedInstanceState: Bundle?) {
        var contactsFragment: ContactsFragmentNew? = null
        if (contactsFragment == null) {
            contactsFragment = ContactsFragmentNew()
        }
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container_view, contactsFragment)
            .commitNow()
        findViewById<ImageView>(R.id.contact_add).setOnClickListener {
            //gotoNewContact()
            requestTesterProtoc()
        }
    }

    private fun requestTesterProtoc() {

        // 创建与服务器的 gRPC 通道
        val channel = ManagedChannelBuilder.forAddress("199.115.231.43", 50051)
            .usePlaintext() // 使用明文（非加密连接）
            .build()


        // 创建存根（stub）
        val asyncStub: GreeterGrpc.GreeterStub = GreeterGrpc.newStub(channel)


        // 创建请求消息
        val request = HelloRequest.newBuilder()
            .setName("John Doe")
            .build()

        VLog.d(TAG, "Sending request: " + request.name)
        // 发送异步请求
        asyncStub.sayHello(request, object : StreamObserver<GreeterOuterClass.HelloReply?> {
            override fun onNext(value: GreeterOuterClass.HelloReply?) {
                VLog.d(TAG, "Server response: " + value?.getMessage())
            }

            override fun onError(t: Throwable) {
                // 处理请求错误
                VLog.e(TAG, "Error during gRPC call", t)
                // 关闭通道
                channel.shutdown()
            }

            override fun onCompleted() {
                // 请求完成
                VLog.d(TAG, "Request completed.")
                // 关闭通道
                channel.shutdown()
            }
        })
    }

    override fun initData(savedInstanceState: Bundle?) {
        myCustomLauncher = registerForActivityResult(MyCustomContract(null,null)) { result ->
            ThreadUtil.runIODelay(3000) {
                SyncDataProgressManager.setLoadingSyncDataFinish()
            }
            VLog.d("CustomContract", "Result: $result")
        }
    }

    override fun initCustomTActionBar(): Int {
        return R.layout.contact_actionbar
    }

    override fun onSetTActionBarVisible(): Boolean {
        return false
    }
    @SuppressLint("CheckResult")
    private fun gotoNewContact() {
        RealRxPermission.getInstance().request(
            ResourceUtils.getString(R.string.permission_contacts_access_request),
            ResourceUtils.getString(R.string.permission_contacts_needed),
            Manifest.permission.WRITE_CONTACTS
        ).subscribe(
            { permission ->
                if (permission.isGranted) {
//                    SystemContactUtils.startLocalFriendAddActivity(null, null, activity())
                    VLog.d("SecondActivity","add contact")
                    myCustomLauncher.launch(BConstant.Contact.REQUEST_CODE_EDIT_CONTACT)
                }
            },
            {
                VLog.d("SecondActivity","error")
            }
        )
    }
//    override fun onActivityResult(
//        requestCode: Int,
//        resultCode: Int,
//        data: Intent?,
//        caller: ComponentCaller
//    ) {
//        super.onActivityResult(requestCode, resultCode, data, caller)
//        ContactGuideHelper.onActivityResult(requestCode)
//    }
}
